<script setup lang="ts">
// -- imports
import { ref } from 'vue';
import AppHeader from '@/components/@lgs/AppHeader/AppHeader.vue';
import Tools from '@likg/tools';
import { aes_encrypt,aes_decrypt} from "@/utils/aes_endecrypt.js";
import wxpayIco from '@/assets/images/wxpay.png';
import { api } from "@/api/apiServer";
import { useRoute, useRouter } from 'vue-router';
import { showLoadingToast, showDialog, closeToast, showToast } from 'vant';
const route = useRoute();
const router = useRouter();
// -- constants
const env = ref(Tools.getEnv());
const checked = ref();
const isShow = ref(false);

const enableIntegral = ref(false);

// -- methods
// 获取预支付订单
const resutData = ref<any>();
const getPrepayOrder = async (paramObj:any) => {
    let res = await api.getPrePay({
       ...paramObj
    });
    if (res.code === 200) {
        resutData.value = res.data;
        if (resutData.value && resutData.value.integralNumber > 0) {
            onChange(true)
        }
    }
};
// 获取url参数
if(route.query?.param) {
    let param = decodeURIComponent(route.query?.param.toString());
    param = param.replace("\n","")
    param = aes_decrypt(param);
    let paramObj = JSON.parse(param);
    if(paramObj){
        getPrepayOrder(paramObj)
    }
}


// 随机生成26个字符串
const randomString = () => {
    let len = 26;
    let chars ='ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
    let maxPos = chars.length;
    let character = '';
    for (let i = 0; i < len; i++) {
        character += chars.charAt(Math.floor(Math.random() * maxPos))
    }
    return character;
}
// 生成加密函数
const createNonceStr = () => {
   const orderGoods = [];
   for (let i = 1; i < 5; i++) {
       orderGoods.push({
           "shopName": "商品"+i,
           "consumeNum": 1,
       })
   }
    const param = {
        "phoneNumber":"18910769383",
        "orderAmount":3,
        "enterpriseId":"1876863951594192896",
        "outTradeNo":randomString(),
        "notifyUrl":"http://127.0.0.1:8018/consumer/consumerOrder/notifyTest",
        "redirectView":"https://user.ynrhjk.cn",
        "sourceType": 2,
        "channelId": localStorage.getItem("channelId"),
        "customerId": localStorage.getItem("customerId"),
        "orderGoodsStr": JSON.stringify(orderGoods),
        "salesmanId":''
    }
    const newStr = aes_encrypt(JSON.stringify(param));
    router.replace("/pay?param="+encodeURIComponent(newStr));
}
//createNonceStr();
const onChange = async (e: any) => {
    // resutData.value.points.forEach((item: any) => {
    //     item.isSelected = false;
    // });
    // resutData.value.points.forEach((item: any) => {
    //     if (item.channelPointId === e) {
    //         item.isSelected = true;
    //     }
    // });
    //     let res = await api.settlement({
    //         ...resutData.value,
    //         enableIntegral:e
    //     });
    //     if (res.code === 200) {
    //         resutData.value.deductionAmount = res.data.deductionAmount;
    //         resutData.value.realAmount = res.data.realAmount;
    //         resutData.value.proxyAvailablePoint = res.data.proxyAvailablePoint;
    //     }
    // } else {
    //         resutData.value.deductionAmount = 0;
    //         resutData.value.realAmount = 0;
    //         resutData.value.proxyAvailablePoint = 0;
    // }
}

// 支付
const toPay = async () => {
    let res = await api.settlementPay({
        ...resutData.value,
        enableIntegral:enableIntegral.value
    });
    if (res.code === 200) {
        let url = res.data.redirectView
        if (res.data.isPay) {
            let payInfo = res.data.payInfo
            // 调用微信公众号支付
            WeixinJSBridge.invoke(
                'getBrandWCPayRequest', {
                'appId': payInfo.packageParams.appId, //公众号ID，由商户传入
                'timeStamp': payInfo.packageParams.timeStamp, //时间戳，自1970年以来的秒数
                'nonceStr': payInfo.packageParams.nonceStr, //随机串
                'package': payInfo.packageParams.package,
                'signType': payInfo.packageParams.signType, //微信签名方式：
                'paySign': payInfo.packageParams.paySign //微信签名
            }, (res: any) => {
                if (res.err_msg == 'get_brand_wcpay_request:ok') {
                    showToast({
                        message: '支付成功！',
                        icon: 'success',
                        onClose: () => {
                            url = url? encodeURIComponent(url):''
                            // 领取积分或抵扣金
                            router.push({ path: 'payResult', query: { isOk: 'success',redirect_uri: url } });
                        }
                    })
                } else {
                    showToast({
                        message: '支付失败！',
                        icon:'fail',
                        onClose: () => {
                            url = url? encodeURIComponent(url):''
                            // 领取积分或抵扣金
                            router.push({ path: 'payResult', query: { isOk: 'error',redirect_uri: url } });
                        }
                    })
                }
            })
        } else {
            // 无需支付，直接积分抵扣成功，跳转到支付成功页面
            url = url? encodeURIComponent(url):''
            // 领取积分或抵扣金
            router.push({ path: 'payResult', query: { isOk: 'success',redirect_uri: url } });
        }
    }
}
</script>

<template>
    <div class="page ">
        <app-header v-if="env !== 'weixin'" title="结算" :show-status-bar="false" />
        <div class="pricebox">
            <div class="color-999999 f14 text-center mt-38">商品总额</div>
            <div class="mt-5 mb-15 f15 px-12 f-500 text-center f43">
                <span class="f21">¥</span>
                <span>{{ (resutData && resutData.orderAmount) || 0 }}</span>
            </div>
            <div class=" px-12 f14 ">
                <!-- <div class="mb-10 bg-FFFFFF py-12 rounded-2 px-18" v-if="resutData && resutData.points.length > 0">
                    <div class="flex-h-between">
                        <span class="color-222222 f-500">积分卡券</span>
                        <span class=" flex-h-between" @click="isShow = !isShow">
                            <span class="color-primary">{{ resutData.points.length || 0 }}张</span>
                            <van-icon name="arrow" color="#B3B3B3" />
                        </span>
                    </div>
                    <div class="flex-h-between mt-10" v-if="isShow">
                        <van-radio-group v-model="checked" @change="onChange" class="w-100">
                            <div class="checkItem" v-for="item in resutData.points" :key="item.channelPointId">
                                <van-radio :name="item.channelPointId" icon-size="18px" checked-color="#F59A23">
                                    <div class="flex-h-between w-100 f14 color-gary">
                                        <span class="color-primary">{{ item.pointFaceValue }}元</span>
                                        <span class="color-primary" v-if="item.isSelected" style="font-size: 12px">(可用{{ resutData.proxyAvailablePoint }}元)</span>
                                        <span style="font-size: 12px">有效期至：{{ item.expireEndTime }}</span>
                                    </div>
                                </van-radio>
                            </div>
                        </van-radio-group>
                    </div>
                </div> -->

                <!-- <div class="mb-10 bg-FFFFFF py-12 rounded-2 px-18" v-if="resutData && resutData.integralNumber > 0">
                    <div class="flex-h-between">
                        <span class="color-222222 f-500">积分卡券</span>
                        <span class=" flex-h-between" @click="isShow = !isShow">
                            <van-icon name="arrow" color="#B3B3B3" />
                        </span>
                    </div>
                    <div class="flex-h-between mt-10" v-if="isShow">
                        <div class="checkItem w-100">
                            <van-checkbox v-model="enableIntegral" @change="onChange" icon-size="18px" checked-color="#F59A23">
                                <div class="flex-h-between w-100 f14 color-gary">
                                    <span class="color-primary">{{ resutData.integralNumber }}元</span>
                                </div>
                            </van-checkbox>
                        </div>
                    </div>
                </div> -->

                <div class="flex-h-between mb-10 bg-FFFFFF py-12 rounded-2 px-18" v-if="resutData && resutData.integralNumber > 0">
                    <span class="color-222222 f-500">活动能量</span>
                    <span class="color-primary">{{ resutData.integralNumber }}J</span>
                </div>
                <div class="flex-h-between mb-10 bg-FFFFFF py-12 rounded-2 px-18">
                    <span class="color-222222 f-500 d-flex align-items-center">
                        <van-image width="14" height="14" :src="wxpayIco" />
                        <span class="ml-4">微信支付</span>
                    </span>
                    <span class="color-primary">{{ (resutData && resutData.realAmount) || 0 }}元</span>
                </div>
                <div class="bind-btn can" @click="toPay">
                    点击结算
                </div>

            </div>
        </div>
    </div>
</template>

<style lang="less">
.pricebox {
    .van-radio__label {
        flex: 1;
    }

    .checkItem {
        background: #F8F8F8;
        border-radius: 5px;
        padding: 15px 15px;
        margin-top: 5px;
    }

    .bind-btn {
        margin-top: 40px;
        height: 44px;
        background: #BFBCB8;
        color: #fff;
        border-radius: 22px;

        display: flex;
        justify-content: center;
        align-items: center;

        font-size: 16px;
        font-weight: 500;
        // opacity: 0.5;

        &.can {
            // opacity: 1;
            background: #F59A23;
        }
    }
}
</style>
